﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using GCC.Container.Abstracts;

using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

using tcm.entity;
using tcm.request.System;
using tcm.response;
using tcm.utils;

namespace tcm.Filters
{
    public class ActionPermissionFilter : IAuthorizationFilter // ActionFilterAttribute//, IAsyncActionFilter
    {
        /// <summary>
        /// 权限字符串，例如 system:user:view
        /// </summary>
        public string Permission { get; set; }
        public bool HasPermi { get; set; } = true;
        public bool HasRole { get; set; } = true;

        private readonly AbsGCCContext _gccContext;

        public ActionPermissionFilter() { }

        public ActionPermissionFilter(string permission, AbsGCCContext gccContext)
        {
            Permission = permission;
            HasPermi = !string.IsNullOrEmpty(Permission);
            _gccContext= gccContext;
        }


        //// <summary>
        ///// 执行Action前校验是否有权限访问
        ///// </summary>
        ///// <param name="context"></param>
        ///// <param name="next"></param>
        ///// <returns></returns>
        //public override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)

        /// <summary>
        /// 验证发生时触发的函数
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnAuthorization(AuthorizationFilterContext filterContext)
        {

            var token = filterContext.HttpContext.Request.Headers["Authorization"].ToString();
            var userInfo= AuthManager.GetUserInfoByToken(_gccContext,token);

            if (userInfo!=null && userInfo?.user_id>0)
            {
                List<string> perms = userInfo.permissions;
                List<string> rolePerms = userInfo.roleIds;
                if (perms.Exists(f => f.Equals(GlobalConstant.AdminPerm)))
                {
                    HasPermi = true;
                }
                else if (rolePerms.Exists(f => f.Equals(GlobalConstant.AdminRole)))
                {
                    HasPermi = true;
                }
                else if (!string.IsNullOrEmpty(Permission))
                {
                    HasPermi = perms.Exists(f => f.ToLower() == Permission.ToLower());
                }

                if (rolePerms.Exists(f => f.Equals(GlobalConstant.DeviceRole)))
                {
                    HasPermi = true;
                }

                var url = filterContext.HttpContext.Request.Path;


                if (!HasPermi && !Permission.Equals("common"))
                {
                    //logger.Info($"用户{info.UserName}没有权限访问{url}，当前权限[{Permission}]");
                    JsonResult result = new(new ApiResult()
                    {
                        code = 403,
                        msg = $"你当前没有权限[{Permission}]访问,请联系管理员",
                        data = url
                    })
                    {
                        ContentType = "application/json",
                    };
                    filterContext.Result = result;
                }
            }
            else
            { 
                
                JsonResult result = new(new ApiResult()
                {
                    code = 401,
                    msg = $"你当前没有登录"
                })
                {
                    ContentType = "application/json",
                };
                filterContext.Result =result ;
            }

        }
    }
}
